<template>
  <div class="delegation-detail" v-if="order">
    <!-- 顶部导航 -->
    <header class="detail-header">
      <button class="back-button" @click="goBack">
        <i class="icon-back">←</i>
      </button>
      <h2>委托详情</h2>
    </header>

    <!-- 主体内容 -->
    <main class="detail-content">
      <!-- 状态栏 -->
      <div class="status-bar">
        <div class="status-wrapper">
          <span class="status-label">委托状态：</span>
          <span class="status-tag" :class="getStatusClass">{{ getStatusText }}</span>
        </div>
        <button 
          @click="showCancelConfirm" 
          class="cancel-btn"
          :class="{ 'disabled': !canCancel }"
          :disabled="!canCancel"
        >
          {{ isCancelled ? '已取消' : '取消配送' }}
        </button>
      </div>

      <!-- 路线信息和功能按钮组 -->
      <div class="route-action-container">
        <div class="delegation-route">
          <div class="route-point">
            <h3>出发地</h3>
            <p>{{ order.pickup_address }}</p>
          </div>
          <div class="route-point">
            <h3>目的地</h3>
            <p>{{ order.delivery_address }}</p>
          </div>
        </div>
        <div class="function-buttons">
          <button @click="contactEntrustor" class="btn-action" :disabled="!canContact">联系代取人</button>
          <button @click="completeDelegation" class="btn-action complete" :disabled="!canComplete">完成配送</button>
        </div>
      </div>

      <!-- 订单信息 -->
      <div class="info-section">
        <div class="info-item">
          <label>取件类型</label>
          <label class="select-label">{{ order.pickup_type === 1 ? '快递' : '外卖' }}</label>
        </div>
        <div class="info-item">
          <label>取件方式</label>
          <label class="select-label">{{ order.pickup_method }}</label>
        </div>
        <div class="info-item">
          <label>物件大小</label>
          <label class="select-label">{{ getSizeLabel(order.size) }}</label>
        </div>
      </div>
      
      <div class="info-section">
        <div class="info-item">
          <label>时间要求</label>
          <label class="select-label">{{ formatDateTime(order.limit_time) }}</label>
        </div>
        <div class="info-item">
          <label>委托金额</label>
          <label class="select-label">¥{{ order.total_amount }}</label>
        </div>
        <div class="info-item">
          <label>联系电话</label>
          <label class="select-label">{{ formatPhoneNumber(order.phone_number) }}</label>
        </div>
      </div>

      <!-- 备注信息 -->
      <div class="detailed-remarks">
        <h3>详细备注</h3>
        <p>{{ order.remarks || '暂无备注' }}</p>
        <div class="additional-info">
          <label>取件信息</label>
          <p>{{ order.detail }}</p>
        </div>
      </div>

      <!-- 图片展示 -->
      <div class="image-container">
        <img :src="getImageUrl(order.img)" alt="订单图片">
        <!-- v-if="order.img" -->
      </div>
    </main>

    <!-- 确认取消弹窗 -->
    <div v-if="showConfirmDialog" class="dialog-overlay">
      <div class="dialog-content">
        <h3>确认取消配送？</h3>
        <p>取消后将无法恢复，是否确认？</p>
        <div class="dialog-buttons">
          <button @click="cancelDelivery" class="btn-action complete">确认</button>
          <button @click="closeDialog" class="btn-action">取消</button>
        </div>
      </div>
    </div>

    <!-- 成功提示弹窗 - 修改按钮绑定事件 -->
    <div v-if="showSuccessDialog" class="dialog-overlay">
      <div class="dialog-content">
        <h1>{{ successMessage }}</h1>
        <button @click="closeSuccessDialog" class="btn-action complete">
          确定
        </button>
      </div>
    </div>

    <!-- 确认完成弹窗 -->
    <div v-if="showCompleteDialog" class="dialog-overlay">
      <div class="dialog-content">
        <h3>要完成配送吗？</h3>
        <p>请确保你已经收到了所委托的货物。完成委托后会向代取人支付委托金</p>
        <div class="dialog-buttons">
          <button @click="showMiddleConfirm" class="btn-action complete">确认</button>
          <button @click="closeCompleteDialog" class="btn-action">取消</button>
        </div>
      </div>
    </div>

    <!-- 中间确认弹窗 -->
    <div v-if="showMiddleDialog" class="dialog-overlay">
      <div class="dialog-content">
        <h1>成功完成委托</h1>
        <button @click="confirmComplete" class="btn-action complete">
          返回详情
        </button>
      </div>
    </div>

    <!-- 移除完成成功提示弹窗 -->
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'

const router = useRouter()
const route = useRoute()
const showConfirmDialog = ref(false)
const showSuccessDialog = ref(false)
const showCompleteDialog = ref(false)
const showCompleteSuccess = ref(false)
const showMiddleDialog = ref(false)
const order = ref(null)

onMounted(async () => {
  try {
    console.log('路由参数 id:', route.params.id)
    console.log('路由状态数据:', history.state?.delegation)
    
    const currentUser = JSON.parse(localStorage.getItem('user'))
    const userId = currentUser?.uid
    if (!userId) {
      console.error('未找到用户ID')
      return
    }
    if (history.state?.delegation) {
      order.value = history.state.delegation
    } else {
      const id = route.params.id
      const response = await axios.post('/api/auth/order_detail',
      { order_id: parseInt(id)},
      {
        
        headers: {
          "Authorization": localStorage.getItem('token')
        }
      })
      order.value = response.data?.data
    }
  } catch (error) {
    console.error('获取订单数据失败:', error)
  }
})

const fetchDelegationData = async () => {
  try {
    // 1. 添加初始延时，确保数据同步
    await new Promise(resolve => setTimeout(resolve, 500))

    // 2. 尝试从 sessionStorage 获取数据
    const cachedData = sessionStorage.getItem('currentDelegation')
    if (cachedData) {
      order.value = JSON.parse(cachedData)
      sessionStorage.removeItem('currentDelegation') // 使用后删除缓存
      return
    }

    // 3. 如果没有缓存数据，则请求后端
    const response = await axios.post(
      '/api/auth/order_detail',
      {
        order_id: parseInt(route.params.id)
      },
      {
        headers: {
          'Authorization': localStorage.getItem('token'),
          'Content-Type': 'application/json'
        }
      }
    )

    console.log('获取订单数据响应:', response)
    if (response.data.code === 0) {
      order.value = response.data.data
    } else {
      console.error('获取订单数据失败:', response.data.message)
    }
  } catch (error) {
    console.error('获取订单数据失败:', error)
  }
}

const contactEntrustor = () => {
  console.log('联系委托人')
}

const editInfo = () => {
  console.log('编辑信息')
}

const completeDelegation = () => {
  showCompleteDialog.value = true
}

const goBack = () => {
  router.go(-1)
}

const showCancelConfirm = () => {
  showConfirmDialog.value = true
}

const closeDialog = () => {
  showConfirmDialog.value = false
}

// 添加成功消息状态
const successMessage = ref('')

// 添加关闭成功弹窗方法
const closeSuccessDialog = () => {
  showSuccessDialog.value = false
  window.location.reload() // 关闭弹窗后刷新页面
}

// 修改取消配送方法
const cancelDelivery = async () => {
  try {
    let response;
    if (order.value.status === 'PUBLISHED') {
      // 已发布状态使用取消前接口
      response = await axios.post('/api/auth/com-cancel-before', 
        { order_id: parseInt(order.value.order_id) },
        {
          headers: {
            'Authorization': localStorage.getItem('token'),
            'Content-Type': 'application/json'
          }
        }
      )
    } else {
      // 其他状态使用取消请求接口
      response = await axios.post('/api/auth/com-cancel-request', 
        { order_id: parseInt(order.value.order_id) },
        {
          headers: {
            'Authorization': localStorage.getItem('token'),
            'Content-Type': 'application/json'
          }
        }
      )
    }

    if (response.data.code === 0) {
      closeDialog()
      successMessage.value = order.value.status === 'PUBLISHED' ? 
        '取消委托成功' : '已提交取消申请'
      showSuccessDialog.value = true
      setTimeout(() => {
        closeSuccessDialog()
      }, 1500)
    } else {
      alert(response.data.message || '取消配送失败')
    }
  } catch (error) {
    console.error('取消配送失败:', error)
    alert('取消配送失败，请重试')
  }
}

const closeCompleteDialog = () => {
  showCompleteDialog.value = false
}

const showMiddleConfirm = () => {
  closeCompleteDialog()
  showMiddleDialog.value = true
  // 3秒后自动触发完成操作
  setTimeout(() => {
    if (showMiddleDialog.value) {
      confirmComplete()
      router.push('/')
    }
  }, 3000)
}

const closeMiddleDialog = () => {
  showMiddleDialog.value = false
}

// 修改完成配送确认方法
const confirmComplete = async () => {
  try {
    const response = await axios.post('/api/auth/finish_request',
      { order_id: parseInt(order.value.order_id) },
      {
        headers: {
          'Authorization': localStorage.getItem('token'),
          'Content-Type': 'application/json'
        }
      }
    )

    if (response.data.code === 0) {
      closeMiddleDialog()
      // 不需要显示额外的成功提示,直接刷新页面
      window.location.reload()
    } else {
      alert(response.data.message || '完成配送失败')
    }
  } catch (error) {
    console.error('完成配送失败:', error)
    alert('完成配送失败，请重试')
  }
}

// 修改状态文本转换计算属性
const getStatusText = computed(() => {
  const statusMap = {
    'PUBLISHED': '待接取',
    'PENDING': '配送中',
    'ARGUE': '争议中',
    'COMPLETED': '已完成',
    'COMPLETED_REQUEST': '已送达',
    'CANCELLED': '已取消',
    'CANCELLED_REQUEST': '取消中'
  }
  return statusMap[order.value?.status] || '未知状态'
})

// 修改状态样式计算属性
const getStatusClass = computed(() => {
  const statusClassMap = {
    'PUBLISHED': 'status-info',
    'PENDING': 'status-warning',
    'ARGUE': 'status-argue',
    'COMPLETED': 'status-success',
    'COMPLETED_REQUEST': 'status-warning',
    'CANCELLED': 'status-danger',
    'CANCELLED_REQUEST': 'status-warning'
  }
  return statusClassMap[order.value?.status] || ''
})

// 修改取消状态检查
const isCancelled = computed(() => {
  return order.value?.status === 'CANCELLED' || order.value?.status === 'CANCELLED_REQUEST'
})

const canCancel = computed(() => {
  const status = order.value?.status
  // 按照 HistoryCard 中的 pickup 类型按钮配置
  switch(status) {
    case 'PUBLISHED': // 已发布
    case 'PENDING': // 配送中
    
      return true
    
    case 'ARGUE': // 争议中
    case 'COMPLETED': // 已完成
    case 'COMPLETED_REQUEST': // 已送达
    case 'CANCELLED': // 已取消
    case 'CANCELLED_REQUEST': // 取消中
      return false
    default:
      return false
  }
})

const canContact = computed(() => {
  const status = order.value?.status
  // 按照 HistoryCard 中的 pickup 类型按钮配置
  switch(status) {
    case 'PENDING': // 配送中
    case 'ARGUE': // 争议中
    case 'CANCELLED_REQUEST': // 取消中
      return true
    case 'PUBLISHED': // 已发布
    case 'COMPLETED': // 已完成
    case 'COMPLETED_REQUEST': // 已送达
    case 'CANCELLED': // 已取消
      return false
    default:
      return false
  }
})

const canComplete = computed(() => {
  const status = order.value?.status
  // 按照 HistoryCard 中的 pickup 类型按钮配置
  switch(status) {
    
    case 'COMPLETED_REQUEST': // 已送达
      return true
    case 'PUBLISHED': // 已发布
    case 'ARGUE': // 争议中
    case 'COMPLETED': // 已完成
    case 'PENDING': // 只有配送中状态可以完成配送
    case 'CANCELLED': // 已取消
    case 'CANCELLED_REQUEST': // 取消中
      return false
    default:
      return false
  }
})

// 调试辅助 - 添加这个函数来检查状态
onMounted(() => {
  watch(() => order.value?.status, (newStatus) => {
    console.log('当前订单状态:', newStatus)
  })
})

// 添加辅助函数
const getSizeLabel = (size) => {
  const sizeMap = {
    1: '小',
    2: '中',
    3: '大'
  }
  return sizeMap[size] || '未知'
}

const formatDateTime = (timestamp) => {
  if (!timestamp) return '无限制'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const formatPhoneNumber = (phone) => {
  if (!phone) return '暂无'
  return phone.replace(/(\d{3})(\d{4})(\d{4})/, '$1 $2 $3')
}

// 添加图片URL处理函数
const getImageUrl = (imgName) => {
  // 这里可以根据实际情况处理图片URL
  // 例如: return `http://your-api-domain/images/${imgName}`
  return 'https://via.placeholder.com/250' // 临时使用一个占位图片
}
</script>

<style scoped>
/* 基础样式 */
.delegation-detail {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
  background: var(--bg-gray);
  color: var(--text-primary);
  font-family: var(--font-family-normal);
}

/* 统一文本样式 */
h1, h2, h3 {
  font-family: var(--font-family-bold);
  margin: 0;
}

h1{
  font-size: var(--font-size-large);
}

p, label {
  font-family: var(--font-family-normal);
}

/* 恢复原有按钮样式 */
.btn-action {
  flex: 1;
  padding: 0.8rem 0;
  background-color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  font-size: var(--font-size-small);
  font-weight: 500;
  transition: all 0.2s ease;
  color: var(--primary-color);
}

.btn-action:hover {
  background-color: #e2e8f0;
}

.btn-action.complete {
  background-color: var(--primary-color);
  max-height: 70px;
  color: white;
}

.btn-action.complete:hover {
  background-color: var(--primary-color-dark);
}

.btn-action:disabled {
  background-color: #f5f5f5;
  color: #999;
  cursor: not-allowed;
}

.btn-action.complete:disabled {
  background-color: #ccc;
  color: #fff;
}

/* 弹窗样式 */
.dialog-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.6); /* 恢复半透明背景 */
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  /* 去掉 pointer-events: none */
}

.dialog-content {
  width: 400px;
  height: 200px;
  background: white;
  border-radius: 16px;
  padding: 24px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  animation: dialogFadeIn 0.3s ease-out;
}

.dialog-content h1,
.dialog-content h3 {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: var(--font-size-large);
  color: var(--text-primary);
}

.dialog-content p {
  flex: 2;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  font-size: var(--font-size-normal);
  color: var(--text-secondary);
}

.dialog-buttons {
  flex: 1;
  display: flex;
  gap: 12px;
  align-items: center;
}

/* 动画 */
@keyframes dialogFadeIn {
  from { opacity: 0; transform: scale(0.95); }
  to { opacity: 1; transform: scale(1); }
}

/* 其他必要的独特样式保持不变 */
.detail-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  display: flex;
  align-items: center;
  padding: 0.8rem;
  background-color: #ffffff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.detail-header h2 {
  position: absolute;  /* 绝对定位 */
  left: 50%;          /* 居中 */
  transform: translateX(-50%);
  font-size: 1.1rem;
  font-weight: 600;
  color: #1e293b;     /* 添加文字颜色 */
  margin: 0;
}

.status-tag {
  padding: 0.4rem 1rem;
  border-radius: 20px;
  font-size: 0.9rem;
  font-weight: 500;
}

.status-green {
  background-color: #e6f7ed;
  color: #27ae60;
}

.detail-content {
  margin-top: 4.5rem; /* 增加顶部边距，确保内容不被 header 遮挡 */
  flex: 1;
  padding: 0.8rem;  /* 减小内容区域padding */
  display: flex;
  flex-direction: column;
  gap: 0.8rem;      /* 减小卡片之间的间距 */
  overflow-y: auto; /* 添加垂直滚动条 */
  -webkit-overflow-scrolling: touch; /* 增加 iOS 滚动流畅度 */
}

.route-action-container {
  background: white;
  border-radius: 16px;
  padding: 1rem;    /* 减小内边距 */
  margin-bottom: 0.8rem;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
}

.delegation-route {
  display: flex;
  justify-content: space-between;
  margin: 0 0 1rem 0;   /* 减小下边距 */
  padding: 0 0 1rem 0;
  border-bottom: 1px solid #edf2f7;
}

.route-point {
  display: flex;
  flex-direction: column;
  background-color: transparent;
  text-align: left;
  gap: 0.5rem;
}

.route-point h3 {
  font-size: 32px;
  color: #a5b2e5;
  margin: 0;
  font-family: 'SourceHanFontBold', sans-serif;
  font-size: var(--font-size-xlarge);
  color: var(--primary-color);
  font-family: var(--font-family-bold);
}

.route-point p {
  font-size: 16px;
  color: #333;
  margin: 0;
  font-family: 'SourceHanFontBold', sans-serif;
  font-size: var(--font-size-large);
  color: var(--text-primary);
  font-family: var(--font-family-bold);
}

.function-buttons {
  display: flex;
  gap: 0.5rem;
  justify-content: space-between;
  padding: 15px 0;
}

.info-section {
  background: #ffffff;
  border-radius: 16px;
  padding: 0.8rem;  /* 减小内边距 */
  display: flex;
  justify-content: space-between;
  gap: 0.5rem;      /* 减小项目之间的间距 */
  margin: 0.5rem 0; /* 减小上下边距 */
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
}

.info-item {
  flex: 1;
  text-align: center;
  padding: 0.5rem;  /* 减小内边距 */
}

label {
  display: block;
  margin-bottom: 0.4rem;  /* 减小标签下边距 */
  font-size: 0.9rem;
  color: #94a3b8;
  font-weight: 500;
}

.select-label {
  width: 100%;
  padding: 8px;
  font-size: 11px;
  border-radius: 5px;
  background-color: rgba(154, 154, 154, 1);
  color: white;
  font-family: 'SourceHanFontBold', sans-serif;
}

.detailed-remarks {
  background-color: white;
  border-radius: 16px;
  padding: 1rem;    /* 减小内边距 */
  margin-top: 0.5rem;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
}

.detailed-remarks h3 {
  margin-bottom: 15px;
  text-align: center;
  color: #333;
  font-size: 16px;
  font-family: 'SourceHanFontBold', sans-serif;
}

.detailed-remarks p {
  font-size: 14px;
  color: #666;
  text-align: justify;
  font-family: 'SourceHanFontBold', sans-serif;
}

.back-button {
  background: none;
  border: none;
  padding: 0.5rem;
  cursor: pointer;
  font-size: 1.2rem;
  color: #475569;
  z-index: 1;        /* 确保按钮在最上层 */
}

.image-container {
  background-color: white;
  border-radius: 16px;
  padding: 1.5rem;
  text-align: center;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
}

.image-container img {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 8px;
}

.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 0.8rem 1rem;
  border-radius: 16px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
}

.status-wrapper {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.status-label {
  font-size: 0.9rem;
  color: #64748b;
  font-weight: 500;
}

.cancel-btn {
  padding: 0.4rem 1rem;
  border: 1px solid #dc2626;
  border-radius: 8px;
  background: white;
  color: #dc2626;
  font-size: 0.9rem;
  cursor: pointer;
  transition: all 0.2s;
}

.cancel-btn:hover {
  background: #dc2626;
  color: white;
}

.cancel-btn.disabled {
  border-color: #9ca3af;
  color: #9ca3af;
  cursor: not-allowed;
  background: #f3f4f6;
}

.cancel-btn.disabled:hover {
  background: #f3f4f6;
  color: #9ca3af;
}

/* 添加状态标签样式 */
.status-success {
  background-color: #e6f7ed;
  color: #27ae60;
}

.status-warning {
  background-color: #fff7e6;
  color: #d48806;
}

.status-danger {
  background-color: #fff1f0;
  color: #dc2626;
}

.status-info {
  background-color: #e6f4ff;
  color: #1890ff;
}

.status-argue {
  background-color: #fff0f6;
  color: #eb2f96;
}

/* 添加完成按钮样式 */
.complete-btn {
  background: #a5b2e5 !important;
  color: white !important;
}

.complete-btn:hover {
  background: #8e9cd0 !important;
}

/* 移除单独的单按钮弹窗样式 */
.dialog-content.single-button {
  /* 移除特殊样式，使用通用弹窗样式 */
}

.full-width {
  width: 100%;
  padding: 0.6rem 0;
  font-size: 1rem;
}
</style>
